package com.ytjj.qmyx.mall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.enums.CounponMoneyEnum;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.SensitiveWordUtil;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.DynamicConstant;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.AppletsPathEnums;
import com.ytjj.qmyx.mall.enums.BannerTypeEnums;
import com.ytjj.qmyx.mall.enums.SourceBannerTypeEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.PopupResponse;
import com.ytjj.qmyx.mall.model.request.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.model.vo.ChannelVO;
import com.ytjj.qmyx.mall.service.CommonService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.mall.service.SpecialService;
import com.ytjj.qmyx.mall.utils.MD5Utils;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.HomeImageResponse;
import com.ytjj.qmyx.users.model.UsersCardDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 公共控制器
 *
 *
 * @version 1.0
 *
 */
@RestController
@RequestMapping("/common")
@Slf4j
@RefreshScope
public class CommonController extends BaseController {

    private final CommonService commonService;

    private final ProductService productService;

    private final SpecialService specialService;

    private final UsersClient usersClient;

    private final RedisService redisService;
    @Resource
    private ImgMapper imgMapper;
    @Resource
    private PbMapper pbMapper;
    @Resource
    private UsersFakeMapper usersFakeMapper;
    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private SysConfigMapper sysConfigMapper;

    @Resource
    private HotSearchMapper hotSearchMapper;

    @Resource
    private OrdersCommentMapper ordersCommentMapper;

    @Resource
    private CnzzMapper cnzzMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private ChannelDao channelDao;

    @Autowired
    private AdminClient adminClient;

    @Value("${quanmingyanxuan.gtPush.homeImageId:1}")
    private Integer homeImageId;

    //首页弹出参数
    @Value("${quanmingyanxuan.gtPush.homeImageId2:2}")
    private Integer homeImageId2;

    public CommonController(CommonService commonService, ProductService productService, SpecialService specialService, UsersClient usersClient, RedisService redisService) {
        this.commonService = commonService;
        this.productService = productService;
        this.specialService = specialService;
        this.usersClient = usersClient;
        this.redisService = redisService;
    }

    /**
     * 获取广告列表
     *
     * @param type
     * @return
     */
    @GetMapping("/getBanners")
    public CommonResult getBanners(@RequestParam("type") String type) {
        return CommonResult.success(commonService.getBannersListByType(type));
    }

    @GetMapping("/getPopup")
    public CommonResult getPopup() {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        log.info("===uuid==={}", uuid);
        UsersResponse currentUser = null;
        try {
            currentUser = this.getCurrentUser();
        } catch (Exception e) {
            log.info("===getpopup===null");
        }
        PopupResponse response = new PopupResponse();
        String sysConfig = "sys:config";
        String amountKey = "app:popup:amount";
        String urlKey = "app:popup:url";
        String jumpUrlKey = "app:popup:jumpurl";
        String noLoginKey = "app:popup:nologin:" + uuid;
        String loginKey = "app:popup:login";

        if (null == currentUser) {
            try {
                String switchVal = redisService.get(noLoginKey);
                if (StringUtils.isEmpty(switchVal)) {
                    response.setOpenOrOff(1);
                    response.setAmount(Integer.parseInt(redisService.getMapString(sysConfig, amountKey)));
                    response.setUrl(redisService.getMapString(sysConfig, urlKey));
                    response.setJumpUrl(redisService.getMapString(sysConfig, jumpUrlKey));
                    redisService.set(noLoginKey, "1");
                    redisService.expire(noLoginKey, 4 * 60 * 60);
                }else {
                    response.setOpenOrOff(2);
                }
            } catch (Exception e) {
                response.setOpenOrOff(1);
                response.setAmount(Integer.parseInt(redisService.getMapString(sysConfig, amountKey)));
                response.setUrl(redisService.getMapString(sysConfig, urlKey));
                response.setJumpUrl(redisService.getMapString(sysConfig, jumpUrlKey));
                redisService.set(noLoginKey, "1");
                redisService.expire(noLoginKey, 4 * 60 * 60);
            }
        } else {
            String nologinSwitchVal = redisService.get(noLoginKey);
            if (!StringUtils.isEmpty(nologinSwitchVal)) {
                response.setOpenOrOff(2);
                return CommonResult.success(response);
            }
            try {
                String switchVal = redisService.getMapString(loginKey, currentUser.getId().toString());
                if (StringUtils.isEmpty(switchVal)) {
                    response.setOpenOrOff(1);
                    response.setAmount(Integer.parseInt(redisService.getMapString(sysConfig, amountKey)));
                    response.setUrl(redisService.getMapString(sysConfig, urlKey));
                    response.setJumpUrl(redisService.getMapString(sysConfig, jumpUrlKey));
                    redisService.add(loginKey, currentUser.getId().toString(), "1");
                }else {
                    response.setOpenOrOff(2);
                }
            } catch (Exception e) {
                response.setOpenOrOff(1);
                response.setAmount(Integer.parseInt(redisService.getMapString(sysConfig, amountKey)));
                response.setUrl(redisService.getMapString(sysConfig, urlKey));
                response.setJumpUrl(redisService.getMapString(sysConfig, jumpUrlKey));
                redisService.add(loginKey, currentUser.getId().toString(), "1");
            }
        }
        return CommonResult.success(response);
    }

    /**
     * 获取首页弹窗
     * @return
     */
    @GetMapping("/getHomeImage")
    public CommonResult getHomeImage() {

        String uuid = TokenUtil.getRequest().getHeader("uuid");
        log.info("===uuid==={}", uuid);
        UsersResponse currentUser = null;
        try {
            currentUser = this.getCurrentUser();
        } catch (Exception e) {
            log.info("===getpopup===null");
        }
        log.info("===homeImageId:{}===null",homeImageId);
        HomeImageResponse homeImage = usersMapper.getHomeImage(homeImageId);
        if (null == homeImage){
            return CommonResult.success();
        }
        PopupResponse response = new PopupResponse();
        String noLoginKey = "app:popup:nologin:" + uuid;
        String loginKey = "app:popup:login";

        if (null == currentUser) {
            try {
                String switchVal = redisService.get(noLoginKey);
                if (StringUtils.isEmpty(switchVal)) {
                    response.setOpenOrOff(1);
                    response.setAmount(0);
                    response.setUrl(homeImage.getImgUrl());
                    response.setJumpUrl(homeImage.getJumpUrl());
                    response.setSmallUrl(homeImage.getSmallUrl());
                    response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                    redisService.set(noLoginKey, "1");
                    redisService.expire(noLoginKey, 4 * 60 * 60);
                }else {
                    response.setOpenOrOff(2);
                    response.setAmount(0);
                    response.setUrl(homeImage.getImgUrl());
                    response.setJumpUrl(homeImage.getJumpUrl());
                    response.setSmallUrl(homeImage.getSmallUrl());
                    response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                }
            } catch (Exception e) {
                response.setOpenOrOff(1);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                redisService.set(noLoginKey, "1");
                redisService.expire(noLoginKey, 4 * 60 * 60);
            }
        } else {
            String nologinSwitchVal = redisService.get(noLoginKey);
            if (!StringUtils.isEmpty(nologinSwitchVal)) {
                response.setOpenOrOff(2);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                return CommonResult.success(response);
            }
            try {
                String switchVal = redisService.getMapString(loginKey, currentUser.getId().toString());
                if (StringUtils.isEmpty(switchVal)) {
                    response.setOpenOrOff(1);
                    response.setAmount(0);
                    response.setUrl(homeImage.getImgUrl());
                    response.setJumpUrl(homeImage.getJumpUrl());
                    response.setSmallUrl(homeImage.getSmallUrl());
                    response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                    redisService.add(loginKey, currentUser.getId().toString(), "1");
                }else {
                    response.setOpenOrOff(2);
                    response.setAmount(0);
                    response.setUrl(homeImage.getImgUrl());
                    response.setJumpUrl(homeImage.getJumpUrl());
                    response.setSmallUrl(homeImage.getSmallUrl());
                    response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                }
            } catch (Exception e) {
                response.setOpenOrOff(1);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                redisService.add(loginKey, currentUser.getId().toString(), "1");
            }
        }
        return CommonResult.success(response);
    }

    /**
     * 获取首页弹窗（登录状态下当日首次只弹窗一次，未登录时每次进入app都弹窗）
     * @return
     */
   /* @GetMapping("/getHomeImage")
    public CommonResult getHomeImage() {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        log.info("===uuid==={}", uuid);
        UsersResponse currentUser = null;
        try {
            currentUser = this.getCurrentUser();
        } catch (Exception e) {
            log.info("===getHomeImageDaily===null");
        }
        log.info("===homeImageId2:{}===null",homeImageId2);
        HomeImageResponse homeImage = usersMapper.getHomeImage(homeImageId2);
        if (null == homeImage){
            return CommonResult.success();
        }
        PopupResponse response = new PopupResponse();
        String noLoginKey = "app:popup-daily:nologin:" + uuid;
        String loginKey = "app:popup-daily:login:";

        if (null == currentUser) {
            String switchVal = redisService.get(noLoginKey);
            if (StringUtils.isEmpty(switchVal)) {
                response.setOpenOrOff(1);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                redisService.set(noLoginKey, "1");
                redisService.expire(noLoginKey, 4 * 60 * 60);
            } else {
                response.setOpenOrOff(2);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
            }
        } else {
            String nologinSwitchVal = redisService.get(noLoginKey);
            if (!StringUtils.isEmpty(nologinSwitchVal)) {
                response.setOpenOrOff(2);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                return CommonResult.success(response);
            }
            String switchVal = redisService.get(loginKey+currentUser.getId().toString());
            if (StringUtils.isEmpty(switchVal)) {
                response.setOpenOrOff(1);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
                redisService.set(loginKey+currentUser.getId().toString(),"1");
                Long curTimeDiff = DateUtils.getCurTimeDiff();
                //设置过期时间
                redisService.expire(loginKey+currentUser.getId().toString(),curTimeDiff);
            } else {
                response.setOpenOrOff(2);
                response.setAmount(0);
                response.setUrl(homeImage.getImgUrl());
                response.setJumpUrl(homeImage.getJumpUrl());
                response.setSmallUrl(homeImage.getSmallUrl());
                response.setSmallJumpUrl(homeImage.getSmallJumpUrl());
            }
        }
        return CommonResult.success(response);
    }*/

    /**
     * 获取首页
     *
     * @return
     */
    @GetMapping("/getHome")
    public CommonResult getHome(@RequestParam("specialType") String specialType) {
//        String s = redisService.get(RedisConstants.HOME_PRODUCT);
        List<BannersResponse> bannersList = commonService.getBannersListByType(SourceBannerTypeEnums.getSourceBannerType(getSource()));
        HomeResponse homeResponse = new HomeResponse();
//        if(StringUtils.isNotEmpty(s)) {
//            homeResponse = JSONObject.parseObject(s, HomeResponse.class);
            homeResponse.setBannersList(bannersList);
//        } else {
            List<SpecialResponse> specialList = specialService.getSpecialListByType(specialType, 1);
            homeResponse.setPopUpType(sysConfigUtil.getSysConfig(SysConfigConstants.POP_UP_TYPE));
            homeResponse.setSpecialList(specialList);
            homeResponse.setWelfareBanners(commonService.getBannersInfoByType(BannerTypeEnums.WELFARE.name()));
            List<ProductResponse> homeRecommendProductList = productService.getHomeRecommendProductList();
            homeRecommendProductList = homeRecommendProductList.stream().map(item -> {
                item.setRecImgFlag(1);
                return item;
            }).collect(Collectors.toList());
            homeResponse.setRecommendProductList(homeRecommendProductList);
//            redisService.set(RedisConstants.HOME_PRODUCT, JSONObject.toJSONString(homeResponse));
//            redisService.expire(RedisConstants.HOME_PRODUCT, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
////        }
        List<BannersResponse> homeBannersList = commonService.getBannersListByType(BannerTypeEnums.HOME.name());
        if (!DynamicConstant.SOURCE_H5.equals(getSource())
                && !DynamicConstant.SOURCE_QA.equals(getSource())) {
            UsersResponse usersResponse;
            if (StringUtils.isEmpty(TokenUtil.getToken())) {
                usersResponse = new UsersResponse()
                        .setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)))
                        .setMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                homeBannersList = homeBannersList.stream().filter(item -> !item.getRemarks().equals("CARD_IMG")).collect(Collectors.toList());
                homeResponse.setHomeBannersList(homeBannersList);
            } else {
                usersResponse = getCurrentUser();
                // 查询是否领券
                List<UsersCardDto> cardList = usersClient.queryCardByUserId(usersResponse.getId());
                if (StringUtils.isNotBlank(usersResponse.getOpenid())
                        && SourceBannerTypeEnums.weapp.name().equals(getSource())
                        && CollectionUtils.isEmpty(cardList)) {
                    homeResponse.setHomeBannersList(homeBannersList);
                } else {
                    homeBannersList = homeBannersList.stream().filter(item -> !item.getRemarks().equals("CARD_IMG")).collect(Collectors.toList());
                    homeResponse.setHomeBannersList(homeBannersList);
                }
            }
            homeResponse.setUsersInfo(usersResponse);
        }
        List<Object> list = redisService.range(RedisConstants.ORDERS_COMMENT, 0, -1);
        List<OrdersCommentResponse> ordersCommentResponses = list.stream()
                .map(item -> {
                    OrdersComment ordersComment = JSONObject.parseObject(item.toString(), OrdersComment.class);
                    OrdersCommentResponse ordersCommentResponse = new OrdersCommentResponse();
                    BeanUtils.copyProperties(ordersComment, ordersCommentResponse);
                    return ordersCommentResponse;
                }).collect(Collectors.toList());
        homeResponse.setOrdersCommentList(ordersCommentResponses);
        return CommonResult.success(homeResponse);
    }

    /**
     * 获取首页
     *
     * @return
     */
    @GetMapping("/getHomeV2")
    public CommonResult getHomeV2() {
        String key = RedisConstants.HOME_PRODUCT_V2 + TokenUtil.getPlatformData();
        String result = redisService.get(key);
        HomeV2Response homeV2Response = new HomeV2Response();
        if(StringUtils.isNotEmpty(result)) {
            homeV2Response = JSONObject.parseObject(result, HomeV2Response.class);
        } else {
            // 首页banner
            List<BannersResponse> bannersList;
            if ("h5".equals(TokenUtil.getSource())) {
                bannersList = commonService.getBannersListByType("LIFE_HOUSE");
            }else {
                bannersList = commonService.getBannersListByType("LIFE_HOUSE_APP");
            }
            // 首页专区列表
            List<SpecialResponse> specialList = specialService.getSpecialListByType("mall", 1);
            // 一键领取福利banner
            BannersResponse welfareBanners = commonService.getBannersInfoByType(BannerTypeEnums.WELFARE.name());
            // 生活馆 (秒杀)
            SeckillDataResponse seckillData = commonService.querySeckillData();
            // 秒杀
            List<ProductResponse> seckillList = commonService.querySeckillList();
            // 积分中心
            List<ProductResponse> cashScoreList = commonService.queryCashScoreList();
            // 新品推荐
            List<ProductResponse> newProductList = commonService.queryNewProductList();
            // 以旧换新
            List<ProductResponse> oldForNewList = commonService.queryOldForNewList();
            // 大图
            List<ProductResponse> recommendProductList = productService.getHomeRecommendProductV2List();
            // 品牌闪购
            List<BrandProductResponse> brandProduct = commonService.queryBrandProductList();
            // 0元测评
            List<ProductResponse> zeroProductList = commonService.queryZeroProductList();
            // 优惠券
            List<ProductResponse> cashCouponList = commonService.queryCashCouponList();
            // 抄底捡漏
            PickUpLeakResponse pickUpLeakResponse = commonService.queryPickUpLeak();

            homeV2Response.setWelfareBanners(welfareBanners);
            homeV2Response.setBannersList(bannersList);
            homeV2Response.setSpecialList(specialList);
            homeV2Response.setSeckillData(seckillData);
            homeV2Response.setSeckillList(seckillList);
            homeV2Response.setCashScoreList(cashScoreList);
            homeV2Response.setNewProductList(newProductList);
            homeV2Response.setOldForNewList(oldForNewList);
            homeV2Response.setRecommendProductList(recommendProductList);
            homeV2Response.setBrandProduct(brandProduct);
            homeV2Response.setZeroProductList(zeroProductList);
            homeV2Response.setCashCounponList(cashCouponList);
            homeV2Response.setPickUpLeakResponse(pickUpLeakResponse);

            redisService.set(key, JSONObject.toJSONString(homeV2Response));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 用户积分
        if(!"h5".equals(TokenUtil.getSource())){
            UsersResponse h5CurrentUser = this.getH5CurrentUser();
            if(h5CurrentUser == null){
                homeV2Response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
            }else{
                homeV2Response.setScore(h5CurrentUser.getScore());
            }
        }
        // 用户红包
//        UsersResponse usersResponse = this.getUsersActivityMax();
//        homeV2Response.setActivityMax(Optional.ofNullable(usersResponse.getActivityMax()).orElse(new BigDecimal(680)).setScale(0, BigDecimal.ROUND_HALF_UP));
        ReturnCouponResponse returnCouponResponse;
        if ("h5".equals(TokenUtil.getSource())) {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON + TokenUtil.getToken());
        }else {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid());
        }
        homeV2Response.setActivityMax(Optional.ofNullable(returnCouponResponse.getActivityMax()).orElse(new BigDecimal(680)));
        return CommonResult.success(homeV2Response);
    }

    private ReturnCouponResponse getReturnCoupon(String key) {
        ReturnCouponResponse returnCouponResponse = new ReturnCouponResponse();

        if (StringUtils.isNotEmpty(redisService.get(key))) {// 记录用户返现红包金额
            returnCouponResponse = JSONObject.parseObject(redisService.get(key), ReturnCouponResponse.class);
        }

        returnCouponResponse.setUsedActivityMax(Optional.ofNullable(returnCouponResponse.getUsedActivityMax())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setTotalReturnCoupon(Optional.ofNullable(returnCouponResponse.getTotalReturnCoupon())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setActivityMax(Optional.ofNullable(returnCouponResponse.getActivityMax())
                .orElse(BigDecimal.valueOf(680)).setScale(0,BigDecimal.ROUND_HALF_UP));
        return returnCouponResponse;
    }

    private UsersResponse getUsersActivityMax() {
        String token;
        UsersResponse usersResponse = new UsersResponse();
        if ("h5".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        }else {
            token = TokenUtil.getUuid();
        }
        if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(redisService.get(token))) {
            usersResponse = JSONObject.parseObject(redisService.get(token), UsersResponse.class);
            usersResponse.setActivityMax(Optional.ofNullable(usersResponse.getActivityMax()).orElse(new BigDecimal(680)));
            redisService.set(token, JSON.toJSONString(usersResponse));
        }
        return usersResponse;
    }


    /**
     * 获取最新版本信息
     *
     * @return
     */
    @GetMapping("/getVersionsInfo")
    public CommonResult getVersionsInfo(@RequestParam("type") String type) {
        String version = TokenUtil.getRequest().getHeader("version");
        return CommonResult.success(commonService.getVersionsInfo(type,version));
    }

    @GetMapping("/getVersion")
    public CommonResult getVersion(@RequestParam("type")String type) {
        String versionNo = TokenUtil.getRequest().getHeader("version");//版本号
        return CommonResult.success(commonService.getVersion(type, versionNo));
    }

    /**
     * 获取图床库
     *
     * @return
     */
    @GetMapping("/getImgList")
    public CommonResult getImgList() {
        List list = redisService.range(RedisConstants.REDIS_KEY_IMG, 0, -1);
        List<Img> imgList = (List<Img>) list.stream()
                .map(item -> {
                    Img img = JSONObject.parseObject(item.toString(), Img.class);
                    return img;
                }).collect(Collectors.toList());
        Map<String, List<Img>> map = imgList.stream()
                .collect(Collectors.groupingBy(Img::getType));
        Map<String, Map<String, Img>> response = new HashMap<>();
        map.forEach((key, value) -> {
            response.put(key, value.stream().collect(Collectors.toMap(Img::getNo, item -> item)));
        });
        return CommonResult.success(response);
    }


    /**
     * 意见反馈
     *
     * @param feedbackRequest
     * @return
     */
    @PostMapping("/ideaResponse")
    public CommonResult ideaResponse(@RequestBody FeedbackRequest feedbackRequest) {
        // 获取该用户信息
        UsersResponse currentUser = this.getCurrentUser();
        String source = this.getSource();
        feedbackRequest.setUserId(currentUser.getId());
        feedbackRequest.setSource(source);
        commonService.submitIdea(feedbackRequest);
        return CommonResult.success("提交成功");
    }


    /**
     * 获取cnzz列表
     * @return
     */
    @GetMapping("/getCnzzList")
    public CommonResult getCnzzList(){
        CnzzExample cnzzExample = new CnzzExample();
        String channel = TokenUtil.getRequest().getHeader("channel");
        if(StringUtils.isEmpty(channel)){
            return CommonResult.success(new ArrayList<>());
        }
        cnzzExample.createCriteria()
                .andChannelEqualTo(channel);
        List<Cnzz> cnzzList = cnzzMapper.selectByExample(cnzzExample);
        return CommonResult.success(cnzzList);
    }


    /**
     * 获取假用户数据
     *
     * @param number
     * @return
     */
    @GetMapping("/getFakeUsers")
    public CommonResult getFakeUsers(@RequestParam("number") Long number) {
        // 从redis中获取假用户数据
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        List<UsersFake> list = fakeUserList.stream().limit(number)
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .collect(Collectors.toList());
        Collections.shuffle(list);
        return CommonResult.success(list);
    }

    /**
     * 获取假用户数据
     *
     * @return
     */
    @GetMapping("/getFakeUsersAndImg")
    public CommonResult getFakeUsersAndImg(@RequestParam("number") Long number) {
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<FakeUserAndImg> fakeUserAndImg = commonService.getFakeUsersAndImg(fakeUserList, number);
        return CommonResult.success(fakeUserAndImg);
    }

    /**
     * 获取假用户and商品数据
     *
     * @return
     */
    @GetMapping("/getFakeUsersAndProduct")
    public CommonResult getFakeUsersAndProduct() {
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<FakeUsersAndProduct> fakeUsersAndProducts = commonService.getFakeUsersAndProduct(fakeUserList);
        try{
            int max=productService.selectProduct(),min=1;
            int  result;
            List<String> name =productService.selectProductName();
            for(FakeUsersAndProduct fakeUsersAndProduct : fakeUsersAndProducts){
                result = (int) (Math.random()*(max-min)+min);
                fakeUsersAndProduct.setProduct(name.get(result));
            }
        }catch (Exception e){
            log.info("系统错误！");
        }
        return CommonResult.success(fakeUsersAndProducts);
    }

    @Resource
    private BankerSiteMapper bankerSiteMapper;

    /**
     * 获取假用户数据v2
     *
     * @param number
     * @return
     */
    @GetMapping("/getFakeUsersData")
    public CommonResult getFakeUsersData(@RequestParam("number") Long number,@RequestParam("type") Integer type) {
        // 从redis中获取假用户数据
        Map<String,Object> result = new HashMap<>();
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> list = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .limit(number)
                .collect(Collectors.toList());
        result.put("fakeUserList",list);
        Integer num = 0;
        switch (type){
            case 1:
                num = Integer.parseInt(sysConfigUtil.getSysConfig("FAKE_NUM_1"));
                break;
            case 2:
                num = Integer.parseInt(sysConfigUtil.getSysConfig("FAKE_NUM_2"));
                break;
            case 3:
                BankerSiteExample bankerSiteExample = new BankerSiteExample();
                bankerSiteExample.createCriteria()
                        .andBankerTypeEqualTo(1)
                        .andStatusEqualTo(1);
                List<BankerSite> bankerSiteList = bankerSiteMapper.selectByExample(bankerSiteExample);
                List<String> bankerSiteLogos = bankerSiteList.stream()
                        .map(item -> item.getLogo())
                        .collect(Collectors.toList());
                Collections.shuffle(bankerSiteLogos);
                num = Integer.parseInt(sysConfigUtil.getSysConfig("FAKE_NUM_3"));
                result.put("bankerSiteLogos",bankerSiteLogos);
                break;
            case 4:
                num = Integer.parseInt(sysConfigUtil.getSysConfig("FAKE_NUM_4"));
                break;
        }
        result.put("num",num);
        return CommonResult.success(result);
    }

    @Resource
    private EnvelopeConfigMapper envelopeConfigMapper;

    /**
     * 加载缓存
     */
    @GetMapping("/reflushCash")
    public void reflushCash() {
        /**
         * 图库
         */
        List<Img> list = imgMapper.selectByExample(new ImgExample());
        redisService.delete(RedisConstants.REDIS_KEY_IMG);
        list.stream().forEach(item ->
                redisService.leftPush(RedisConstants.REDIS_KEY_IMG, JSONObject.toJSONString(item)));

        /**
         * 敏感内容
         */
        List<Pb> pbList = pbMapper.selectByExample(new PbExample());
        redisService.delete(RedisConstants.PD_KEY);
        pbList.stream().forEach(item ->
                redisService.leftPush(RedisConstants.PD_KEY, JSONObject.toJSONString(item)));
        SensitiveWordUtil.init(new HashSet(pbList.stream().map(Pb::getContent).collect(Collectors.toList())));

        /**
         * 假用户
         */
        List<UsersFake> fakeUserList = usersFakeMapper.selectByExample(new UsersFakeExample());
        redisService.delete(RedisConstants.FAKE_USER);
        fakeUserList.stream().forEach(item ->
                redisService.leftPush(RedisConstants.FAKE_USER, JSONObject.toJSONString(item)));


        /**
         * 获取系统配置
         */
        List<SysConfig> sysConfigs = sysConfigMapper.selectByExample(new SysConfigExample());
        redisService.delete(RedisConstants.SYS_CONFIG);
        sysConfigs.stream().forEach(item -> {
            try {
                redisService.add(RedisConstants.SYS_CONFIG, item.getParamKey(), item.getParamValue());
            } catch (Exception e) {
                log.error("=== refresh cache is error by sysConfig:{}, {}", item.getParamKey(), e);
            }
        });

        /**
         * @Description 获取我的钱包 - 红包数额配置第一天
         *
         *
         *
         * @Version 1.0
         **/
        EnvelopeConfigExample former = new EnvelopeConfigExample();
        former.createCriteria()
                .andIdBetween(1, 4);
        List<EnvelopeConfig> formerEnvelopeConfigList = envelopeConfigMapper.selectByExample(former);
        redisService.delete(RedisConstants.RED_ENVELOPE_CONFIG_FORMER);
        formerEnvelopeConfigList.stream().forEach(item -> {
            redisService.leftPush(RedisConstants.RED_ENVELOPE_CONFIG_FORMER, JSONObject.toJSONString(item));
        });

        /**
         * @Description 获取我的钱包 - 红包数额配置- 非第一天
         *
         *
         *
         * @Version 1.0
         **/
        EnvelopeConfigExample latter = new EnvelopeConfigExample();
        latter.createCriteria()
                .andIdBetween(5, 8);
        List<EnvelopeConfig> envelopeConfigList = envelopeConfigMapper.selectByExample(latter);
        redisService.delete(RedisConstants.RED_ENVELOPE_CONFIG_LATTER);
        envelopeConfigList.stream().forEach(item -> {
            redisService.leftPush(RedisConstants.RED_ENVELOPE_CONFIG_LATTER, JSONObject.toJSONString(item));
        });

        /**
         * 热搜索词
         */
        List<HotSearch> searchList = hotSearchMapper.selectByExample(new HotSearchExample());
        redisService.delete(RedisConstants.HOT_SEARCH);
        searchList.stream().forEach(item ->
                redisService.leftPush(RedisConstants.HOT_SEARCH, JSONObject.toJSONString(item)));


        List<OrdersComment> ordersCommentList = ordersCommentMapper.selectByExample(new OrdersCommentExample());
        redisService.delete(RedisConstants.ORDERS_COMMENT);
        ordersCommentList.stream().forEach(item ->
                redisService.leftPush(RedisConstants.ORDERS_COMMENT, JSONObject.toJSONString(item)));

        /**
         * 渠道跳转配置
         */
        List<ChannelVO> channels = channelDao.findChannelList();
        redisService.delete(RedisConstants.CHANNEL);
        channels.stream().forEach(item -> {
            try {
                redisService.add(RedisConstants.CHANNEL, item.getChannel(), item.getRedirectUrl());
            } catch (Exception e) {
                log.error("=== refresh cache is error by channel:{}, {}", item.getChannel(), e);
            }
        });

    }


    @GetMapping("/getSysConfig")
    public String getSysConfig(@RequestParam("key") String key) {
        return sysConfigUtil.getSysConfig(key);
    }

    @GetMapping("/getSysConfig2")
    public CommonResult getSysConfig2(@RequestParam("key") String key) {
        return CommonResult.success(sysConfigUtil.getSysConfig(key));
    }

    /**
     * 加载缓存
     */
    @GetMapping("/reflushChannelRedirect")
    public void reflushChannelRedirect() {

        //渠道跳转配置
        List<ChannelVO> channels = channelDao.findChannelList();
        redisService.delete(RedisConstants.CHANNEL);
        channels.stream().forEach(item -> {
            redisService.add(RedisConstants.CHANNEL, item.getChannel(), item.getRedirectUrl());
        });

    }

    @GetMapping("/getSysConfigValue")
    public String getSysConfigValue(@RequestParam("key") String key) {
        return sysConfigMapper.selectByPrimaryKey(key).getParamValue();
    }


    /**
     * 页面统计
     * @param usersAnalysisRequest
     * @return
     */
    @PostMapping("/analysisData")
    public CommonResult analysisData(@RequestBody UsersAnalysisRequest usersAnalysisRequest ) {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {

        }
        try {
            commonService.saveAnalysisData(usersAnalysisRequest, usersResponse);
            return CommonResult.success();
        } catch (Exception e) {
            log.error("analysisData接口错误,{}",e);
            return CommonResult.failed();
        }
    }

    /**
     * 额外统计
     * @param extraAnalysisRequest
     * @return
     */
    @PostMapping("/extraAnalysisData")
    public CommonResult extraAnalysisData(@RequestBody ExtraAnalysisRequest extraAnalysisRequest ) {
        UsersResponse currentUser = this.getH5CurrentUser();
        String channel = null;
        if(currentUser!=null){
            channel = currentUser.getChannel();
        }
        commonService.extraAnalysisData(extraAnalysisRequest,channel);
        return CommonResult.success();
    }

    /**
     * 作废接口
     * @param path
     * @param param
     * @return
     */
    @PostMapping("/shareInfo")
    public CommonResult shareInfo(@RequestParam(value = "path") String path, @RequestParam(value = "param",required = false) String param ) {
        return CommonResult.success(commonService.shareInfo(path,param));
    }

    /**
     * 获取微信token
     */
    @GetMapping("/getWxConfigure")
    public CommonResult getWxConfigure(){
        Map<String,Object> wxConfigureMap = commonService.getWxConfigure();
        return CommonResult.success(wxConfigureMap);
    }

    /**
     * 个推接口(根据cid推送消息)
     * @return
     */
    @PostMapping("/gtPushInfoByCid")
    public CommonResult gtPushInfoByCid(@RequestBody GtPushRequest gtPushRequest){
        Map<String, Object> stringObjectMap = commonService.gtPushInfoByCid(gtPushRequest);
        log.info("个推返回信息："+stringObjectMap.toString());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 采集用户cid
     * @param cidInfoRequest
     * @return
     */
    @PostMapping("/getCidInfo")
    public CommonResult getCidInfo(@RequestBody CidInfoRequest cidInfoRequest){
        UsersResponse currentUser = getCurrentUser();
        commonService.getCidInfo(cidInfoRequest,currentUser);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 客服收集
     * @param customerCollectRequest
     * @return
     */
    @PostMapping("/getCustomerCollect")
    public CommonResult getCustomerCollect(@RequestBody CustomerCollectRequest customerCollectRequest){
        commonService.getCustomerCollect(customerCollectRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 话费列表
     * @return
     */
    @GetMapping("/getPhoneChargesList")
    public CommonResult getPhoneChargesList(){
        List<PhoneRechargeConfig> phoneChargesList = commonService.getPhoneChargesList();
        return CommonResult.success(phoneChargesList);
    }

    /**
     * 充值列表
     * @return
     */
    @GetMapping("/rechargeList")
    public CommonResult rechargeList(){
        return CommonResult.success(commonService.rechargeList());
    }

    /**
     * 板块列表数据
     */
    @GetMapping("/getforumLiveData")
    public CommonResult getforumLiveData(){
        String key = "LIFE_HOUSE_INNER_DATA";
        String str = redisService.get(key);
        ForumLiveResponse result;
        if(str == null){
            result = commonService.getforumLiveData();
            redisService.set(key, JSON.toJSONString(result));
            redisService.expire(key,Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
            return CommonResult.success(result);
        }
        result = JSONObject.parseObject(str,ForumLiveResponse.class);
        return CommonResult.success(result);
    }

    @Resource
    private ChannelMapper channelMapper;

    /**
     * 根据路径 跳转小程序
     * @return
     */
    @GetMapping("/skipApplets")
    public CommonResult skipApplets(@RequestParam(value = "code") String code,
                                    @RequestParam(value = "channel") String channel,
                                    @RequestParam(value = "pid",required = false) Integer pid){
        // 渠道
        channel = channel+"-weapp";
        String key;
        if(AppletsPathEnums.HOT_PRODUCT_DETAIL.getCode().equals(code)){
            key = channel+"_"+code+"_"+pid;
        }else{
            key = channel+"_"+code;
        }
        String s = redisService.get(key);
        String url;
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(SysConfigConstants.WX_TOKEN);
        if(StringUtils.isEmpty(s)){
            url = commonService.skipApplets(code,channel,sysConfig.getParamValue(),pid);
            redisService.set(key,url);
            redisService.expire(key, ExpireTimeConstant.SKIP_APPLETS_PAGE);
        }else{
            url = s;
        }
        ChannelExample example = new ChannelExample();
        example.createCriteria()
                .andChannelEqualTo(channel);
        List<Channel> channelList = channelMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(channelList)){
            Channel channelData = new Channel();
            channelData.setPlatform("weapp");
            channelData.setChannel(channel);
            channelData.setChannelDesc("跳转小程序指定页面");
            channelData.setSort(1);
            channelData.setStatus((byte)1);
            channelData.setCreateTime(new Date());
            channelData.setErrorStatus((byte)0);
            channelData.setPid(0);
            channelMapper.insert(channelData);
        }
        return CommonResult.success(url);
    }

    /**
     * 根据路径 跳转小程序
     * 只是下面方法的基础上改成了走post方式
     * @return
     */
    @PostMapping("/skipAppletsV4")
    public CommonResult skipAppletsV4(@RequestBody SkipAppletsRequest request) {
        log.info("===skipAppletsV4==={}", JSONObject.toJSONString(request));
        String path = request.getPath();
        String channel = request.getChannel();
        String token = TokenUtil.getToken();
        String query = request.getQuery();
        // 渠道
//        channel = channel+"-weapp";
        String key = "";
        try {
            key= MD5Utils.MD5(query+"_"+path + "_" + token);
        } catch (Exception e) {
            log.info("===skipAppletsV4 md5 is error!!!===");
            log.info("======================{}", e);
        }

        String s = redisService.get(key);
        String url;
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(SysConfigConstants.WX_TOKEN);
        if(StringUtils.isEmpty(s)){
            url = commonService.skipAppletsByPath(path,channel, request.getQuery(),sysConfig.getParamValue());
            redisService.set(key,url);
            redisService.expire(key, ExpireTimeConstant.SKIP_APPLETS_PAGE);
        }else{
            url = s;
        }
//        ChannelExample example = new ChannelExample();
//        example.createCriteria()
//                .andChannelEqualTo(channel);
//        List<Channel> channelList = channelMapper.selectByExample(example);
//        if(CollectionUtils.isEmpty(channelList)){
//            Channel channelData = new Channel();
//            channelData.setPlatform("weapp");
//            channelData.setChannel(channel);
//            channelData.setChannelDesc("跳转小程序指定页面");
//            channelData.setSort(1);
//            channelData.setStatus((byte)1);
//            channelData.setCreateTime(new Date());
//            channelData.setErrorStatus((byte)0);
//            channelData.setRedirectUrl(path);
//            channelData.setPid(0);
//            channelMapper.insert(channelData);
//        }
        return CommonResult.success(url);
    }

    /**
     * 根据路径 跳转小程序
     * @return
     */
    @GetMapping("/skipAppletsV3")
    public CommonResult skipAppletsV3(@RequestParam(value = "path") String path,
                                    @RequestParam(value = "channel") String channel) throws Exception {
        // 渠道
        channel = channel+"-weapp";
        String token = TokenUtil.getToken();
        String key= MD5Utils.MD5(channel+"_"+path + "_" + token);

        String s = redisService.get(key);
        String url;
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(SysConfigConstants.WX_TOKEN);
        if(StringUtils.isEmpty(s)){
            url = commonService.skipAppletsByPath(path,channel,sysConfig.getParamValue());
            redisService.set(key,url);
            redisService.expire(key, ExpireTimeConstant.SKIP_APPLETS_PAGE);
        }else{
            url = s;
        }
        ChannelExample example = new ChannelExample();
        example.createCriteria()
                .andChannelEqualTo(channel);
        List<Channel> channelList = channelMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(channelList)){
            Channel channelData = new Channel();
            channelData.setPlatform("weapp");
            channelData.setChannel(channel);
            channelData.setChannelDesc("跳转小程序指定页面");
            channelData.setSort(1);
            channelData.setStatus((byte)1);
            channelData.setCreateTime(new Date());
            channelData.setErrorStatus((byte)0);
            channelData.setRedirectUrl(path);
            channelData.setPid(0);
            channelMapper.insert(channelData);
        }
        return CommonResult.success(url);
    }

    /**
     * 根据路径 跳转小程序
     * @return
     */
    @GetMapping("/skipAppletsV2")
    public CommonResult skipAppletsV2(@RequestParam(value = "code") String code,
                                      @RequestParam(value = "channel") String channel,
                                      @RequestParam(value = "pid",required = false) Integer pid){
        // 渠道
        channel = channel+"-weapp";
        // 根据 code 获取路径
        String path = AppletsPathEnums.getPageName(code);
        String key = channel+"_"+code;
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(SysConfigConstants.WX_TOKEN);
        String url = commonService.skipApplets(path,channel,sysConfig.getParamValue(),pid);
        redisService.set(key,url);
        redisService.expire(key, ExpireTimeConstant.SKIP_APPLETS_PAGE);
        return CommonResult.success(url);
    }

    @GetMapping("/getInfoByChannel")
    public CommonResult getInfoByChannel(@RequestParam(value = "channel") String channel){
        return CommonResult.success(commonService.getInfoByChannel(channel));
    }


    /**
     * 红包体系
     * @param type
     * @return
     */
    @GetMapping("/getCounponMoney")
    public CommonResult getCounponMoney(@RequestParam(value = "type",required = false) CounponMoneyEnum type,@RequestParam(required = false) Integer userId){
        log.info("====getCounponMoney==={}, {}", type.toString(), userId);
        if(type == null){
            return CommonResult.success();
        }
        if (!type.toString().equals("SINGIN") && !type.toString().equals("RELEASE_EVALUATION")) {
            return CommonResult.success();
        }
         if(userId == null) {
             userId =  getCurrentUser().getId();
         }
        return CommonResult.success(commonService.addUserBalance(userId,type));
    }

    /**
     * 红包体系-返零元测评本金
     * @param type
     * @return
     */
    @GetMapping("/backZeroEvaluationCapitalMoney")
    public CommonResult backZeroEvaluationCapitalMoney(@RequestParam(value = "type",required = false) CounponMoneyEnum type,
                                                       @RequestParam(required = false) Integer userId,
                                                       @RequestParam(value = "money") BigDecimal money){
        log.info("====backZeroEvaluationCapitalMoney==={}, {}, {}", type.toString(), userId, money);
        if(type == null){
            return CommonResult.success();
        }
        if (!type.toString().equals("SINGIN") && !type.toString().equals("RELEASE_EVALUATION")) {
            return CommonResult.success();
        }
        if(userId == null) {
            userId =  getCurrentUser().getId();
        }
        return CommonResult.success(commonService.backZeroEvaluationCapitalMoney(userId,type, money));
    }

    /**
     * 积分体系
     * @param type
     * @return
     */
    @GetMapping("/doCounponScore")
    public CommonResult doCounponScore(@RequestParam(value = "type",required = false) CounponMoneyEnum type) {
        Integer userId = null;
        try {
            userId =  getCurrentUser().getId();
        } catch (Exception e) {
            log.info("===未登录===");
        }
        if (null == userId) {
            return CommonResult.success(0);
        }
        String appAddScoreNum = "0";
        Date curDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String curDay = sdf.format(curDate);
        String addScoreKey = RedisConstants.APP_ADDSCORE_NUM + curDay;
        try {
            appAddScoreNum = redisService.get(addScoreKey + userId);
            if (Integer.parseInt(appAddScoreNum) > 4) {
                return CommonResult.success(0);
            }
            redisService.set(addScoreKey + userId, String.valueOf(Integer.parseInt(appAddScoreNum) + 1));
        } catch (Exception e) {
            redisService.set(addScoreKey + userId, "1");
        }
        redisService.expire(addScoreKey + userId, 25 * 60 * 60);
        return CommonResult.success(commonService.doGiveScore(userId, type));
    }

    /**
     * 获取红包体系 完成状态
     */
    @GetMapping("getCounponList")
    public CommonResult getCounponList() {
        Integer userId =  getCurrentUser().getId();
        return CommonResult.success(commonService.getCounponList(userId));
    }
    /**
     * 获取时间戳
     */
    @GetMapping("/getSystemTime")
    public CommonResult getSystemTime() {
        return CommonResult.success(System.currentTimeMillis());
    }

    @GetMapping("/getHomeImageById")
    public CommonResult getHomeImageById(Integer id){
        HomeImageResponse homeImage = usersMapper.getHomeImage(homeImageId);
        return CommonResult.success(homeImage);
    }
}
